import time

import torch
from django.shortcuts import render
from django.http import HttpResponse
from esp import models
from translate import Translator
from esp.utils.model import create_tts_model
import esp.utils.savers


# Create your views here.
def main(request):
    return HttpResponse('esp')


def add_default_data_to_mysql(request):
    meta_data = models.Reading()
    meta_data.sentence = 'This is a sentence read by English.'
    meta_data.save()
    return HttpResponse('done')


trans = Translator(to_lang='zh')


def load_model(request):
    lang = 'Mandarin'
    tag = 'kan-bayashi/csmsc_tacotron2'  # @param ["kan-bayashi/csmsc_tacotron2", "kan-bayashi/csmsc_transformer", "kan-bayashi/csmsc_fastspeech", "kan-bayashi/csmsc_fastspeech2", "kan-bayashi/csmsc_conformer_fastspeech2", "kan-bayashi/csmsc_vits", "kan-bayashi/csmsc_full_band_vits"] {type: "string"}
    vocoder_tag = "parallel_wavegan/csmsc_style_melgan.v1"  # @param ["none", "parallel_wavegan/csmsc_parallel_wavegan.v1", "parallel_wavegan/csmsc_multi_band_melgan.v2", "parallel_wavegan/csmsc_hifigan.v1", "parallel_wavegan/csmsc_style_melgan.v1"] {type:"string"}

    from espnet2.bin.tts_inference import Text2Speech
    from espnet2.utils.types import str_or_none
    global text2speech
    try:
        text2speech = Text2Speech.from_pretrained(
            model_tag=str_or_none(tag),
            vocoder_tag=str_or_none(vocoder_tag),
            device="cuda:0",
            # Only for Tacotron 2 & Transformer
            threshold=0.5,
            # Only for Tacotron 2
            minlenratio=0.0,
            maxlenratio=10.0,
            use_att_constraint=False,
            backward_window=1,
            forward_window=3,
            # Only for FastSpeech & FastSpeech2 & VITS
            speed_control_alpha=1.0,
            # Only for VITS
            noise_scale=0.333,
            noise_scale_dur=0.333,
        )
    except ImportError or ValueError as e:
        return HttpResponse('Loading model failed! Exception as {}'.format(e))
    return HttpResponse('Loaded model successfully!')

tts_model = create_tts_model()


def get_tts_test(request):
    zh_sentence = trans.translate("This is a software used to convert sentence to waveform.")

    with torch.no_grad():
        start = time.time()
        wav = tts_model(zh_sentence)["wav"]
    rtf = (time.time() - start) / (len(wav) / tts_model.fs)
    print(f"RTF = {rtf:5f}")
    esp.utils.savers.save_.save_wav_upload_oss(zh_sentence, wav)

    return HttpResponse(zh_sentence)

def text_form(request):
    return render(request,'g.html')